package org.nofs.database;

import java.sql.*;
import java.text.SimpleDateFormat;

import org.nofs.Grasscutter;
import org.nofs.game.Account;

import static org.nofs.database.DatabaseManager.initialize;

public final class DatabaseHelper {
    private static Connection connection;

    public static Account createAccount(String username) {
        return createAccountWithUid(username, 0);
    }

    public static Account createAccountWithUid(String username, int reservedUid) {
        initialize();
        if (checkIfAccountExists(username)) {
            return null;
        }
        if (reservedUid > 0 && (reservedUid == 99 || checkIfAccountExists(reservedUid))) {
            return null;
        }
        Account account = new Account();
        account.setUsername(username);

        // Here getNextId should be adjusted to take the tablename as a parameter
        account.setId(Integer.toString(DatabaseManager.getNextId("accounts")));

        if (reservedUid > 0) {
            account.setReservedPlayerUid(reservedUid);
        }
        saveAccount(account);
        return account;
    }

    // ... All other create account methods would need similar adjustments ...

    public static void saveAccount(Account account) {
        Grasscutter.getLogger().info("即将插入数据 : " + account.toString());
        initialize();
        try {
            Connection conn = DatabaseManager.getConnection();
            PreparedStatement stmt = conn.prepareStatement("INSERT INTO accounts (id, username, password, reservedPlayerId,email,token,sessionKey,permissions,locale,banReason,banEndTime,banStartTime,isBanned) VALUES (0, ?, ?,?,?,?,?,?,?,?,?,?,?)");
            //stmt.setString(1, account.getId());
//            stmt.setString(2, account.getUsername());
//            stmt.setString(3, account.getPassword());
//            stmt.setInt(4, account.getReservedPlayerUid());
//            stmt.setString(5, account.getEmail());
//            stmt.setString(6, account.getToken());
//            stmt.setString(7, account.getSessionKey());
//            stmt.setString(8, account.getPermissions().toString());
//            stmt.setString(9, account.getLocale().toString());
//            stmt.setString(10, account.getBanReason());
//            stmt.setInt(11, account.getBanEndTime());
//            stmt.setInt(12, account.getBanStartTime());
//            stmt.setBoolean(13, account.isBanned());
            stmt.setString(1, account.getUsername());
            stmt.setString(2, account.getPassword());
            stmt.setInt(3, account.getReservedPlayerUid());
            stmt.setString(4, account.getEmail());
            stmt.setString(5, account.getToken());
            stmt.setString(6, account.getSessionKey());
            stmt.setString(7, account.getPermissions().toString());
            stmt.setString(8, account.getLocale().toString());
            stmt.setString(9, account.getBanReason());
            stmt.setInt(10, account.getBanEndTime());
            stmt.setInt(11, account.getBanStartTime());
            stmt.setBoolean(12, account.isBanned());
            // ... set other placeholders ...
            int affectedRows = stmt.executeUpdate();
            if (affectedRows == 0) {
                throw new SQLException("Saving account failed, no rows affected.");
            } else {
                Grasscutter.getLogger().info("用户数据插入成功: " + account.toString());
            }
        } catch (SQLException e) {
            // Handle exception
            Grasscutter.getLogger().error(e.toString());
        }
    }

    // 写入sessionKey
    public static void saveSessionKey(String username, String sessionKey) {
        Grasscutter.getLogger().info("username: " + username + "即将写入sessionKey: " + sessionKey);
        initialize();
        try {
            Connection conn = DatabaseManager.getConnection();
            PreparedStatement stmt = conn.prepareStatement("UPDATE accounts SET sessionKey = ? WHERE username = ?");
            stmt.setString(1, sessionKey);
            stmt.setString(2, username);
            int affectedRows = stmt.executeUpdate();
            if (affectedRows == 0) {
                throw new SQLException("Saving account failed, no rows affected.");
            }
        } catch (SQLException e) {
            // Handle exception
        }
    }
    // 写入token
    public static void saveToken(String username, String token) {
        Grasscutter.getLogger().info("username: " + username + "即将写入token: " + token);
        initialize();
        try {
            Connection conn = DatabaseManager.getConnection();
            PreparedStatement stmt = conn.prepareStatement("UPDATE accounts SET token = ?,login_time = ? WHERE username = ?");
            stmt.setString(1, token);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = dateFormat.format(new Date(System.currentTimeMillis()));
            stmt.setTimestamp(2, Timestamp.valueOf(currentTime));
            stmt.setString(3, username);
            int affectedRows = stmt.executeUpdate();
            if (affectedRows == 0) {
                throw new SQLException("Saving account failed, no rows affected.");
            }
        } catch (SQLException e) {
            // Handle exception
        }
    }


    //查询sessionKey
    public static String getSessionKey(String username) {
        initialize();
        try {
            Connection conn = DatabaseManager.getConnection();
            PreparedStatement stmt = conn.prepareStatement("SELECT sessionKey FROM accounts WHERE username = ?");
            stmt.setString(1, username);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return rs.getString("sessionKey");
            }
        } catch (SQLException e) {
            // Handle exception
        }
        return null;
    }

    // ... All `getAccountBy...` methods would be replaced with JDBC queries ...

    public static boolean checkIfAccountExists(String name) {
        initialize();
        try {
            Connection conn = DatabaseManager.getConnection();
            PreparedStatement stmt = conn.prepareStatement("SELECT COUNT(*) FROM accounts WHERE username = ?");
            stmt.setString(1, name);
            Grasscutter.getLogger().info("username: " + name);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return rs.getInt(1) > 0;
            }
        } catch (SQLException e) {
            // Handle exception
            Grasscutter.getLogger().error(e.toString());
        }
        return false;
    }

    public static boolean checkIfAccountExists(int reservedUid) {
        initialize();
        try {
            Connection conn = DatabaseManager.getConnection();
            PreparedStatement stmt = conn.prepareStatement("SELECT COUNT(*) FROM accounts WHERE reservedPlayerId = ?");
            stmt.setInt(1, reservedUid);

            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return rs.getInt(1) > 0;
            }
        } catch (SQLException e) {
            // Handle exception
            Grasscutter.getLogger().error(e.toString());
        }
        return false;
    }

//    public static Account getAccountByName(String username) {
//        initialize();
//        try (Connection conn = DatabaseManager.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM accounts WHERE username = ?")) {
//            stmt.setString(1, username);
//            ResultSet rs = stmt.executeQuery();
//            if (rs.next()) {
//                Grasscutter.getLogger().info("Found account with username: " + username);
//                return extractAccountFromResultSet(rs);
//            } else {
//                Grasscutter.getLogger().info("No account found with username: " + username);
//            }
//        } catch (SQLException e) {
//            // Handle exception
//            Grasscutter.getLogger().error("[Line 103] " + e.toString());
//        }
//        return null;
//    }

    public static Account getAccountByName(String account) {
        // 如果account 不包含@直接返回null
        if (!account.contains("@")) {
            return null;
        }
        Grasscutter.getLogger().info("account: " + account);
        initialize();
        try (Connection conn = DatabaseManager.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM accounts WHERE username = ? AND password = ?")) {
            String[] parts = account.split("@");
            String username = parts[0];
            String password = parts[1];
            stmt.setString(1, username);
            stmt.setString(2, password);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                Grasscutter.getLogger().info("Found account with username: " + username);
                return extractAccountFromResultSet(rs);
            } else {
                Grasscutter.getLogger().info("No account found with username: " + username);
            }
        } catch (SQLException e) {
            // Handle exception
            Grasscutter.getLogger().error("[Line 103] " + e.toString());
        }
        Grasscutter.getLogger().info("即将返回");
        return null;
    }

    // 用username 和 password来获取
    public static Account getAccountByNameAndPassword(String username, String password) {
        Grasscutter.getLogger().info("username: " + username + "\tpassword: " + password);
        initialize();
        try (Connection conn = DatabaseManager.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM accounts WHERE username = ?")) {
            stmt.setString(1, username);
            //stmt.setString(2, password);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                Grasscutter.getLogger().info("Found account with username: " + username);
                return extractAccountFromResultSet(rs);
            } else {
                Grasscutter.getLogger().info("No account found with username: " + username);
            }
        } catch (SQLException e) {
            // Handle exception
            Grasscutter.getLogger().error("[Line 103] " + e.toString());
        }
        return null;
    }

    // Helper method to convert ResultSet into Account object
    private static Account extractAccountFromResultSet(ResultSet rs) throws SQLException {
        Account account = new Account();
        account.setId(rs.getString("id"));
        account.setUsername(rs.getString("username"));
        account.setPassword(rs.getString("password"));
        account.setReservedPlayerUid(rs.getInt("reservedPlayerId"));
        account.setEmail(rs.getString("email"));
        account.setToken(rs.getString("token"));
//        account.setBanReason(rs.getString("banReason"));
//        account.setBanEndTime(rs.getInt("banEndTime"));
//        account.setBanStartTime(rs.getInt("banStartTime"));
//        account.setBanned(rs.getBoolean("isBanned"));
        // ... extract other fields ...
        return account;
    }

    public static Account getAccountByToken(String token) {
        initialize();
        if (token == null) {
            return null;
        }
        try (Connection conn = DatabaseManager.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM accounts WHERE token = ?")) {
            stmt.setString(1, token);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                return extractAccountFromResultSet(rs);
            }
        } catch (SQLException e) {
            // Handle exception
            Grasscutter.getLogger().error(e.toString());
        }
        return null;
    }

    public static Account getAccountBySessionKey(String sessionKey) {
        initialize();
        if (sessionKey == null) {
            return null;
        }
        try (Connection conn = DatabaseManager.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM accounts WHERE sessionKey = ?")) {
            stmt.setString(1, sessionKey);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                return extractAccountFromResultSet(rs);
            }
        } catch (SQLException e) {
            // Handle exception
            Grasscutter.getLogger().error(e.toString());
        }
        return null;
    }

    public static Account getAccountById(String uid) {
        initialize();
        try (Connection conn = DatabaseManager.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM accounts WHERE id = ?")) {
            stmt.setString(1, uid);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                Grasscutter.getLogger().info("Found account with id: " + uid);
                return extractAccountFromResultSet(rs);
            }
        } catch (SQLException e) {
            // Handle exception
            Grasscutter.getLogger().error(e.toString());
        }
        return null;
    }

    public static Account getAccountByPlayerId(int playerId) {
        initialize();
        try (Connection conn = DatabaseManager.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM accounts WHERE reservedPlayerId = ?")) {
            stmt.setInt(1, playerId);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                return extractAccountFromResultSet(rs);
            }
        } catch (SQLException e) {
            // Handle exception
            Grasscutter.getLogger().error(e.toString());
        }
        return null;
    }
}


//package org.nofs.database;
//
//import com.mongodb.DBCollection;
//import dev.morphia.Datastore;
//import dev.morphia.query.experimental.filters.Filters;
//import org.nofs.game.Account;
//
///* loaded from: sdkserver.jar:emu/grasscutter/database/DatabaseHelper.class */
//public final class DatabaseHelper {
//    public static Account createAccount(String username) {
//        return createAccountWithUid(username, 0);
//    }
//
//    public static Account createAccountWithUid(String username, int reservedUid) {
//        if (checkIfAccountExists(username)) {
//            return null;
//        }
//        if (reservedUid > 0 && (reservedUid == 99 || checkIfAccountExists(reservedUid))) {
//            return null;
//        }
//        Account account = new Account();
//        account.setUsername(username);
//        account.setId(Integer.toString(DatabaseManager.getNextId(account)));
//        if (reservedUid > 0) {
//            account.setReservedPlayerUid(reservedUid);
//        }
//        saveAccount(account);
//        return account;
//    }
//
//    @Deprecated
//    public static Account createAccountWithPassword(String username, String password) {
//        Account exists = getAccountByName(username);
//        if (exists != null) {
//            return null;
//        }
//        Account account = new Account();
//        account.setId(Integer.toString(DatabaseManager.getNextId(account)));
//        account.setUsername(username);
//        account.setPassword(password);
//        saveAccount(account);
//        return account;
//    }
//
//    public static void saveAccount(Account account) {
//        DatabaseManager.getAccountDatastore().save(account);
//    }
//
//    public static Account getAccountByName(String username) {
//        return (Account) DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("username", username)).first();
//    }
//
//    public static Account getAccountByToken(String token) {
//        if (token == null) {
//            return null;
//        }
//        return (Account) DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("token", token)).first();
//    }
//
//    public static Account getAccountBySessionKey(String sessionKey) {
//        if (sessionKey == null) {
//            return null;
//        }
//        return (Account) DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("sessionKey", sessionKey)).first();
//    }
//
//    public static Account getAccountById(String uid) {
//        return (Account) DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq(DBCollection.ID_FIELD_NAME, uid)).first();
//    }
//
//    public static Account getAccountByPlayerId(int playerId) {
//        return (Account) DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("reservedPlayerId", Integer.valueOf(playerId))).first();
//    }
//
//    public static boolean checkIfAccountExists(String name) {
//        return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("username", name)).count() > 0;
//    }
//
//    public static boolean checkIfAccountExists(int reservedUid) {
//        return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("reservedPlayerId", Integer.valueOf(reservedUid))).count() > 0;
//    }
//}
